import json
import random
import re

from django.shortcuts import render
import logging
logger = logging.getLogger('django')
# Create your views here.
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from users.models import User


class UsernameCountView(View):
    def get(self,request,username):
        try:
            count = User.objects.filter(username=username).count()
        except:
            return JsonResponse({'code':400,'errmsg':'访问数据库失败'})

        return JsonResponse({'code': 200,
                             'errmsg': 'ok',
                             'count':count})


class UserRegisterView(View):
    def post(self,request):
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        allow = dict.get('allow')
        image_code_client = dict.get('image_code')
        uuid = dict.get('image_code_id')
        invitation = dict.get('invitation')


        # 2. 校验参数
        if not all([username, password, password2,allow,image_code_client, uuid]):
            return JsonResponse({'code': 400,
                                'errmsg': '缺少必传参数'})
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}',username):
            return JsonResponse({'code': 400,
                                'errmsg': '用户名格式错误'})
        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 400,
                                'errmsg': 'password格式有误'})
        # 5.password2 和 password
        if password != password2:
            return JsonResponse({'code': 400,
                                'errmsg': '两次输入不对'})
        # 6.allow检验
        if allow != True:
            return JsonResponse({'code': 400,
                                'errmsg': 'allow格式有误'})
        # 7. 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        # 8. 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return JsonResponse({'code': 400,
                                'errmsg': '图形验证码失效'})
        # 9. 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
        # 10. 对比图形验证码
        # bytes 转字符串
        image_code_server = image_code_server.decode()
        # 转小写后比较
        if image_code_client.lower() != image_code_server.lower():
            return JsonResponse({'code': 400,
                                'errmsg': '输入图形验证码有误'})
        if invitation != None:
            try:
                invitation_conn = User.objects.filter(myinvitation=invitation).count()
            except:
                return JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
            if invitation_conn < 1:
                return JsonResponse({'code': 400, 'errmsg': '邀请码不存在'})


        while True:
            myinvitation = '%06d' % random.randint(0, 999999)
            try:
                conn = User.objects.filter(myinvitation=myinvitation).count()
            except:
                return JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
            if conn == 0:
                break
        logger.info(myinvitation)

        try:
            if invitation is None:
                user = User.objects.create_user(username=username,
                                                password=password,
                                                myinvitation=myinvitation)
            else:
                user = User.objects.create_user(username=username,
                                                password=password,
                                                invitation=invitation,
                                                myinvitation=myinvitation)
        except Exception as e:
            return JsonResponse({'code': 400,
                                'errmsg': '保存到数据库出错'})

        return JsonResponse({'code': 0,
                            'errmsg': 'ok'})
